package spcpy

import (
	"gitee.com/ymofen/gobase"
	"gitee.com/ymofen/golog"
	"gitee.com/ymofen/sputils"
)

type SubProbe struct {
	Id      string
	log     golog.Logger
	sub     *sputils.SpBaseSub
	hexFlag int8
}

func (this *SubProbe) Init() {
	this.sub = sputils.NewSpBaseSub("")
	this.log = golog.Default().WithOptionEx(golog.WithOptionPrefix(this.Id))
}

func (this *SubProbe) Close() error {
	this.sub.Close()
	return nil
}

func (this *SubProbe) onInput(id, topic string, args ...interface{}) (ok bool) {
	action := args[0].(int)
	if action == sputils.SpTypeData {
		buf := args[1].([]byte)
		if this.hexFlag == 1 {
			this.log.Infof("<<l:%d, hex:%s", len(buf), gobase.BufToHexStr(buf, 0, ""))
		} else {
			this.log.Infof("<<l:%d, %s", len(buf), string(buf))
		}

	}
	return
}

func (this *SubProbe) UpdateConf(subconf string) {
	err := this.sub.ReloadConfString(subconf, this.onInput)
	if err != nil {
		this.log.Warnf("sub fail %v", err.Error())
	}
}
